import api from '../../../api/index';
const defaultAvatarUrl =
	'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
Page({
	/**
   * 页面的初始数据
   */
	data: {
		userlist: null,
		defaultAvatarUrl,
		show: false,
		list: [],
		contentData: [],
		qaHistoryList: []
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		this.getlist();
		if (wx.getStorageSync('userInfo')) {
			this.getuserinfo()
		  }
	},
	getuserinfo() {
		// 整体列表查询
		try {
			api.post('/api/hxhealth/user/load').then((res) => {
				// console.log(res);
				console.log('----res----', res[0]);
				this.setData({
					userlist: res[0]
				});
			});
		} catch (e) {
			console.error(e);
		}
	},
	getlist() {
		// 整体列表查询
		try {
			api.post('/api/hxhealth/qa/list').then((res) => {
				// console.log(res);
				console.log('----res----', res[0]);
				console.log(res[0]);
				this.setData({
					list: res,
					show: true
				});
			});
		} catch (e) {
			console.error(e);
		}
	},
	go(e) {
		const value = e.currentTarget.dataset.content;
		let array = this.data.contentData;
		array.push({text: value, type: 'send'});
		this.setData({
			contentData: array
		});
		this.sendQAData(value)
	},
	async getHealthServicer() {
    const actions = {
			data: {
					name: '',
        			regioncode: '',
        			roleids: '',
				  }
			}
	// const res = await api.get(`/api/hxhealth/servicer/health`, actions, true)
	try {
		api.get(`/api/hxhealth/servicer/health`,actions,true).then((res) => {
		  if (res.data && res.data.length > 0) {
			wx.navigateTo({
			   url: `/healthCounseling/pages/detail/index?conversationID=${res.data[0].imuserid}`
		   });
   			} else {
				   console.log('0000');
   			}
		}).catch(e => {
			console.log(e)
			wx.showToast({
				title: '暂无健康咨询师！',
				icon: 'none',
				duration: 2000
			});
		})
	  } catch (e) {
		console.error(e);
	  }
    
  },
	/**
   * 跳转客服
   */
	goCustomer() {
		this.getHealthServicer()
	},
	goteacher() {
		wx.navigateTo({ url: 'url' });
	},
	onChange(e) {
		this.setData({
			inputValue: e.detail,
		})
	},
	goBottom(){
    wx.createSelectorQuery().select('#chat-container').boundingClientRect(function(rect){
      console.log('rectheight',rect.height);
      /* 将页面移动到最底部（用xxx的height定位） */
      wx.pageScrollTo({
        scrollTop: rect.height
      })
    }).exec()
  },
	getQAHistory() {
		const actions = {
			data: {
				lessid: this.data.list[0].id
			}
		}
		api.post(`/api/hxhealth/qa/history`, actions).then(res => {
			console.log(res,'resres')
			if (res && res.length > 0) {
				res.forEach(item => {
					item.type = item.role === 'system' ? 'recover' : 'send'
				})
				this.setData({
					qaHistoryList: res
				})
				console.log(this.data.qaHistoryList,'qaHistoryList')
			}
		}).catch(error => {
			wx.showToast({
				title: error.faultstring,
				icon: 'none',
				duration: 3000
			})
			return
		})
	},
	sendQAData(data) {
		const actions = {
			data: {
				text: data
			}
		}
		api.post(`/api/hxhealth/qa/text`, actions).then(res => {
			if (res && res.length > 0) {
				res[0].type = 'recover'
				let array = this.data.contentData;
				array.push(res[0]);
				this.setData({
					contentData: array
				});
				this.goBottom()
			}
		}).catch(error => {
			wx.showToast({
				title: error.faultstring,
				icon: 'none',
				duration: 3000
			})
			return
		})
	},
	confirmTap() {
		let array = this.data.contentData;
		array.push({text: this.data.inputValue, type: 'send'});
		this.setData({
			contentData: array
		});
		this.goBottom()
		this.sendQAData(this.data.inputValue)
		this.setData({
			inputValue: null
		})
	},
	copyText(event) {
		const text = event.target.dataset.text;
		wx.setClipboardData({
		  data: String(text), // 将文本强制转换为字符串
		  success: function () {
			console.log('文本已复制');
		  },
		  fail: function (error) {
			console.error('复制失败:', error);
		  }
		});
	  },
	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady() {},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {
		this.getQAHistory()
	},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},
	
	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
